package com.domainchen.framework.common.util;

import java.io.UnsupportedEncodingException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author domainchen
 * @version 2016年3月9日 下午8:28:33 类说明 字符串工具类
 */
public class StringUtils extends org.apache.commons.lang3.StringUtils {

	private static Logger log = LoggerFactory.getLogger(StringUtils.class);
	public final static String EMPTY = "";

	/**
	 * 字符串分隔符
	 */
	public static  String SEPARATOR = String.valueOf((char) 29);

	/**
	 * 空字符串和NULL值的判断
	 * 
	 * @param str
	 *            ：输入的字符串值
	 * @return
	 */
	public static boolean isEmpty(String str) {
		if (str == null || "".equals(str.trim()) || "null".equals(str.trim().toLowerCase())) {
			return true;
		}
		return false;
	}

	public static boolean isNull(String str) {
		if (null == str || "".equals(str.trim()) || str.isEmpty()) {
			return true;
		}
		return false;
	}

	/**
	 * 非空字符串的判断
	 * 
	 * @param str
	 *            ：输入的字符串值
	 * @return
	 */
	public static boolean isNotEmpty(String str) {
		return !StringUtils.isEmpty(str);
	}

	/**
	 * 将NULL值转换为空字符串
	 * 
	 * @param str：输入的字符串值
	 * @return
	 */
	public static String convertNull(String str) {
		if (StringUtils.isEmpty(str)) {
			return "";
		}
		if ("null".equalsIgnoreCase(str))
			return "";
		return str;
	}

	public static String arr2string(int[] obj) {
		StringBuffer sb = new StringBuffer();
		String ret = "";
		if (obj instanceof int[]) {
			for (int i : obj) {
				sb.append(i).append(",");
			}
			ret = StringUtils.isEmpty(sb.toString()) ? "" : sb.toString().substring(0, sb.toString().length() - 1);
		} else {
			new RuntimeException("整型数组转换成 字符串错误");
		}
		return ret;
	}

	public static String arr2string(String[] obj) {
		StringBuffer sb = new StringBuffer();
		String ret = "";
		if (obj instanceof String[]) {
			for (String a : obj) {
				sb.append("'").append(a).append("',");
			}
			ret = StringUtils.isEmpty(sb.toString()) ? "" : sb.toString().substring(0, sb.toString().length() - 1);
		} else {
			new RuntimeException("字符串数组转换成 字符串错误");
		}
		return ret;
	}

	public static String arr2stringNoQuotes(String[] obj) {
		StringBuffer sb = new StringBuffer();
		String ret = "";
		if (obj instanceof String[]) {
			for (String a : obj) {
				sb.append(a).append(",");
			}
			ret = StringUtils.isEmpty(sb.toString()) ? "" : sb.toString().substring(0, sb.toString().length() - 1);
		} else {
			new RuntimeException("字符串数组转换成 字符串错误");
		}
		return ret;
	}

	public static String arr2string(String[] obj, String split) {
		StringBuffer sb = new StringBuffer();
		String ret = "";
		if (obj instanceof String[]) {
			for (String a : obj) {
				sb.append(split).append(a).append(split).append(",");
			}
			ret = StringUtils.isEmpty(sb.toString()) ? "" : sb.toString().substring(0, sb.toString().length() - 1);
		} else {
			new RuntimeException("字符串数组转换成 字符串错误");
		}
		return ret;
	}

	public static String arr2string(Object[] obj) {
		return StringUtils.arr2string(obj, "'");
	}

	public static String arr2string(Object[] obj, String split) {
		StringBuffer sb = new StringBuffer();
		String ret = "";
		if (obj instanceof Object[]) {
			for (Object o : obj) {
				if (o instanceof String) {
					String a = (String) o;
					sb.append(split).append(a).append(split).append(",");
				} else
					sb.append(split).append(String.valueOf(o)).append(split).append(",");
			}
			ret = StringUtils.isEmpty(sb.toString()) ? "" : sb.toString().substring(0, sb.toString().length() - 1);
		} else {
			new RuntimeException("字符串数组转换成 字符串错误");
		}
		return ret;
	}

	public static boolean equal(String a, String b) {
		if (a == null)
			return false;
		if (b == null)
			return false;
		if (a.equals(b)) {
			return true;
		}
		return false;

	}

	/**
	 * 移除重复的空格
	 * 
	 * @param s
	 * @return
	 */
	public static String removeMultiSpace(String s) {
		return s.replaceAll("\\s+", " ");
	}

	/**
	 * 将字符串首字母变大写
	 * 
	 * @param s
	 * @return
	 */
	public static String toUpperCaseFristLetter(String s) {
		if (s != null && s.length() > 1) {
			return s.substring(0, 1).toUpperCase() + s.substring(1);
		}
		return null;
	}

	/**
	 * 替换首字母大写
	 * 
	 * @param s
	 * @return
	 */
	public static String upperFirst(String s) {
		return s.replaceFirst(s.substring(0, 1), s.substring(0, 1).toUpperCase());
	}

	/**
	 * 每length长度字符串换行输出
	 * 
	 * @param s
	 * @param length
	 * @return
	 * @see
	 */
	public static String newLineOutput(String s, int length) {
		if (s == null || s.length() == 0 || length == 0)
			return s;
		int size = s.length() / length;
		StringBuffer result = new StringBuffer();
		for (int i = 0; i < size - 1; i++) {
			result.append(s.substring(length * i, length * (i + 1))).append("<br/>");
		}
		result.append(s.substring(length * (size - 1), s.length()));
		return result.toString();
	}

	/**
	 * 获取uuid
	 * 
	 * @return
	 */
	public static String getUuid() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replace("-", "");
	}

	public static String getEmptyIfNull(String str) {
		String tmp = "";
		if (isNotEmpty(str)) {
			return str;
		}
		return tmp;
	}

	/**
	 * 生成32位UUID
	 * 
	 * @return
	 */
	/*
	 * public String createUUID32Code() { return new
	 * String(Hex.encodeHex(UUIDHexGenerator.randomUUID().getRawBytes())); }
	 */
	/*
	 * public static void main(String[] args) { //log.debug(getBASE64(" 发啊飞"));
	 * //log.debug(UUID.randomUUID()); // //log.debug(StringUtils.newLineOutput(
	 * "你好很好 方法 发啊飞但是", 2)); }
	 */

	public static String replace(String s, String target, String replacement) {
		return s.replace(target, replacement);
	}

	// 过滤大部分html字符
	public static String filterSpecialStr(String input) {
		if (input == null) {
			return input;
		}
		StringBuilder sb = new StringBuilder(input.length());
		for (int i = 0, c = input.length(); i < c; i++) {
			char ch = input.charAt(i);
			switch (ch) {
			case '&':
				sb.append("&amp;");
				break;
			case '<':
				sb.append("&lt;");
				break;
			case '>':
				sb.append("&gt;");
				break;
			case '"':
				sb.append("&quot;");
				break;
			case '\'':
				sb.append("&#x27;");
				break;
			case '/':
				sb.append("&#x2F;");
				break;
			default:
				sb.append(ch);
			}
		}
		return sb.toString();
	}

	public static String hideStr(int firstShowCount, int backShowCount, String str) {
		if (StringUtils.isNotEmpty(str)) {
			int strLength = str.length();
			String strLen = "";
			if (strLength < 18) {// 即身份证等
				strLen = "*";
			} else {
				for (int i = 0; i < strLength - firstShowCount - backShowCount; i++) {
					strLen += "*";
				}
			}
			String returnStr = str.substring(0, firstShowCount) + strLen
					+ str.substring(strLength - backShowCount, strLength);
			return returnStr;
		}
		return str;
	}

	/**
	 * 验证长度
	 * 
	 * @param str
	 * @param leng
	 * @return
	 */
	public static boolean equalLeng(String str, int leng) {
		if (isNull(str)) {
			return false;
		}
		if (leng == str.length()) {
			return true;
		} else
			return false;

	}

	public static String lowerFirst(String str) {
		if (StringUtils.isBlank(str)) {
			return "";
		} else {
			return str.substring(0, 1).toLowerCase() + str.substring(1);
		}
	}

	/**
	 * 替换掉HTML标签方法
	 */
	public static String replaceHtml(String html) {
		if (isBlank(html)) {
			return "";
		}
		String regEx = "<.+?>";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(html);
		String s = m.replaceAll("");
		return s;
	}

	/**
	 * 缩略字符串（不区分中英文字符）
	 * 
	 * @param str
	 *            目标字符串
	 * @param length
	 *            截取长度
	 * @return
	 */
	public static String abbr(String str, int length) {
		if (str == null) {
			return "";
		}
		try {
			StringBuilder sb = new StringBuilder();
			int currentLength = 0;
			for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
				currentLength += String.valueOf(c).getBytes("GBK").length;
				if (currentLength <= length - 3) {
					sb.append(c);
				} else {
					sb.append("...");
					break;
				}
			}
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			log.error("错误异常:", e);
		}
		return "";
	}

	/**
	 * 缩略字符串（替换html）
	 * 
	 * @param str
	 *            目标字符串
	 * @param length
	 *            截取长度
	 * @return
	 */
	public static String rabbr(String str, int length) {
		return abbr(replaceHtml(str), length);
	}

	/**
	 * 转换为Double类型
	 */
	public static Double toDouble(Object val) {
		if (val == null) {
			return 0D;
		}
		try {
			return Double.valueOf(trim(val.toString()));
		} catch (Exception e) {
			return 0D;
		}
	}

	/**
	 * 转换为Float类型
	 */
	public static Float toFloat(Object val) {
		return toDouble(val).floatValue();
	}

	/**
	 * 转换为Long类型
	 */
	public static Long toLong(Object val) {
		return toDouble(val).longValue();
	}

	/**
	 * 转换为Integer类型
	 */
	public static Integer toInteger(Object val) {
		return toLong(val).intValue();
	}

	/**
	 * 获得用户远程地址
	 */
	public static String getRemoteAddr(HttpServletRequest request) {
		String remoteAddr = request.getHeader("X-Real-IP");
		if (isNotBlank(remoteAddr)) {
			remoteAddr = request.getHeader("X-Forwarded-For");
		} else if (isNotBlank(remoteAddr)) {
			remoteAddr = request.getHeader("Proxy-Client-IP");
		} else if (isNotBlank(remoteAddr)) {
			remoteAddr = request.getHeader("WL-Proxy-Client-IP");
		}
		return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
	}

	public static char[] StringToArray(String str) {
		try {
			if (StringUtils.isNull(str)) {
				return null;
			}
		} catch (Exception e) {
			return null;
		}
		return str.toCharArray();
	}

	/**
	 * 判断是否可以发送 {0}{0}{0} 某个占位符的值为1即可
	 * 
	 * @param sendStr
	 * @return
	 */
	public static boolean sendFlag(char[] sendStr) {
		if (null == sendStr) {
			return false;
		}
		if (("1").equals(String.valueOf(sendStr[0]))) {
			return true;
		}
		if ("1".equals(String.valueOf(sendStr[1]))) {

			return true;
		}
		if ("1".equals(String.valueOf(sendStr[2]))) {
			return true;
		}
		if ("1".equals(String.valueOf(sendStr[3]))) {
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		StringUtils sUtils = new StringUtils();
		log.debug("截取有用没身份证====" + sUtils.hideStr(3, 3, ""));
		log.debug("截取有用没手机号码====" + sUtils.hideStr(1, 0, ""));
	}

}
